import { Tooltip, Dropdown, Menu, MenuItem, Tag } from "ant-design-vue";
import { shallowMerge } from "~shared/";
import { isNil } from "lodash-es";
import type {
	Operatoin,
	OnOperation,
	Column,
	ColumnTag,
	ColumnTagList,
	OperationRender,
	OperRenderCol,
} from "./types";
import { useRoleListStore } from "~/store/modules/role";
import { computed } from "vue";

const roleListStore = useRoleListStore();

// 用户的按钮权限
const permissionIds = computed(() => {
	return roleListStore.permissionIds || [];
});

export function renderColumnEllipsis({ value }: UsedDict<{ value: string }>) {
	return (
		<Tooltip title={value}>
			<span
				class="d-inline-block x-full single-cut"
				style={{ verticalAlign: "bottom" }}
			>
				{value}
			</span>
		</Tooltip>
	);
}

export function renderColumnEllipsisOfSize(
	size: number,
	{ value }: UsedDict<{ value: string }>
) {
	if (value.toString().length >= size) {
		return renderColumnEllipsis({ value });
	}

	return value;
}

/**
 * 对表格中增加字体缺省处理
 * @param column
 * @returns
 */
export function buildTbleColumnEllipsis(column: Column) {
	const { ellipsis } = column;

	if (typeof ellipsis === "boolean" || ellipsis?.not || ellipsis.showTitle) {
		column.customRender = renderColumnEllipsis;
		return column;
	}

	if (Number.isInteger(ellipsis.size)) {
		column.customRender = renderColumnEllipsisOfSize.bind(null, ellipsis.size);
		return column;
	}

	return column;
}

function renderTag(node: ColumnTagList) {
	if (typeof node === "string" || typeof node === "number") {
		return <Tag>{node}</Tag>;
	}

	if (Array.isArray(node)) {
		return node.map((el) => renderTag(el));
	}

	const el = node as ColumnTag;

	return (
		<Tag style={shallowMerge(el.style, { "vertical-align": "text-bottom" })} color={el.color}>
			{el.label}
		</Tag>
	);
}

export function buildTagText(el: Column) {
	el.customRender = function (renderColumn) {
		const node = renderColumn.value;
		return renderTag(node ?? {});
	};

	return el;
}

function renderOperationNode(
	node: MergeType<
		Operatoin,
		UsedDict<{ opt: RowInputForTable; mergeClass?: string }>
	>
) {
	const {
		label,
		operation,
		opt,
		mergeClass = "",
		onClick,
		disabled,
		customRenderLabelNode,
		style,
		color,
	} = node;

	let cls = "primary-color primart-hover-color cursor-pointer font-size-16 font-weight-700 " + mergeClass;

	if (disabled) {
		cls = "disabled-text font-size-16 font-weight-700 " + mergeClass;
	}

	if (typeof customRenderLabelNode === "function") {
		return customRenderLabelNode.call(node, opt);
	}

	const complateStyle = shallowMerge(
		{},
		style,
		isNil(color) ? null : { color }
	);

	// 如果禁用的，就不展示
	return (
		<span key={operation} onClick={onClick} style={complateStyle} class={cls}>
			{label}
		</span>
	);
}

function renderTableOperationForConfig(
	opers: OperRenderCol,
	onOperationChange: OnOperation,
	renderTableRow: RowInputForTable
) {
	const fliters = opers;

	const finishOperations = fliters.filter((item) => {
		// 当前无按钮权限
		const hasNoPermission = item.permissionCode && !permissionIds.value.includes(item.permissionCode);
		return hasNoPermission ? false : true;
	});
	const lastOpers: Operatoin[] | null = finishOperations.length > 3 ? finishOperations.slice(2) : null;
	const firstOpers = finishOperations.length > 3
		? finishOperations.slice(0, 2)
		: finishOperations;
	const length = firstOpers.length - 1;
	const lastEmpty = lastOpers === null;

	const completeOperationNodes = firstOpers.map((el, i) => {
		return renderOperationNode({
			...el,
			onClick: el.disabled ? null : onOperationChange.bind(null, el.operation, renderTableRow),
			opt: renderTableRow,
			mergeClass:
				length !== i || !lastEmpty ? "auto-table-operation-split" : "",
		});
	});

	if (!lastEmpty) {
		const node = (
			<Dropdown
				placement="bottomLeft"
				overlay={
					<Menu>
						{lastOpers.map((child) => {
							return (
								<MenuItem
									onClick={onOperationChange.bind(
										null,
										child.operation,
										renderTableRow
									)}
								>
									{renderOperationNode({
										...child,
										opt: renderTableRow,
									})}
								</MenuItem>
							);
						})}
					</Menu>
				}
			>
				<span class="primary-color cursor-pointer font-size-16 font-weight-700 ">
					更多
					<i
						class="icon iconfont font-size:16  icon-zhaoxia"
						style={{ verticalAlign: "bottom" }}
					></i>
				</span>
			</Dropdown>
		);
		completeOperationNodes.push(node);
	}

	return <>{completeOperationNodes}</>;
}

function renderTableOperationForRender(
	renderOper: OperationRender<Operatoin[]>,
	onOperationChange: OnOperation,
	renderTableRow: RowInputForTable
) {
	const opers = renderOper(renderTableRow);

	return renderTableOperationForConfig(
		opers,
		onOperationChange,
		renderTableRow
	);
}

export function buildTableOperation(
	column: Column,
	onOperationChange: OnOperation
) {
	const operations = column.operations;

	const render = renderTableOperationForRender.bind(
		null,
		operations,
		onOperationChange
	);
	const config = renderTableOperationForConfig.bind(
		null,
		operations,
		onOperationChange
	);

	const nextColumn = shallowMerge(
		{
			title: "操作",
			width: column?.width ?? 180,
			customRender: typeof operations === "function" ? render : config,
		},
		column
	);

	return nextColumn;
}
